package com.cqw.commontest.io;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-04-26 09:49
 * @Description:
 */
public class ZipInputStreamTest {


    public static void main(String[] args) throws IOException {
        File file = new File("D://fileTest");
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D://fileTest/file.zip"));
        ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
        zipFile(zipOutputStream, file, "");
        zipOutputStream.close();
    }


    private static void zipFile(ZipOutputStream zipOutputStream, File file, String s) throws IOException {
        //如果压缩文件是文件夹，需要将文件夹中的文件取出来，包括文件及文件夹
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            //putNextEntry(ZipEntry e)开始写一个新的 ZipEntry，并将流内的位置移至此 entry 所值数据的开头
            zipOutputStream.putNextEntry(new ZipEntry(s + "/"));
            for (File fileExtend : files) {
                //递归
                zipFile(zipOutputStream, fileExtend, s + fileExtend.getName() + "/");
            }
        } else {
            //putNextEntry(ZipEntry e)开始写一个新的 ZipEntry，并将流内的位置移至此 entry 所值数据的开头
            zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024 * 1024];
            int len;
            if ((len = fileInputStream.read(bytes)) != -1) {
                zipOutputStream.write(bytes, 0, len);
            }
            fileInputStream.close();
        }


    }

}
